package cn.ncu.controller;

import cn.ncu.entity.Province;
import cn.ncu.entity.Result;
import cn.ncu.service.ProvinceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author:Martina
 * @create:2020-07-15 16:09
 * @description:
 */
@RestController
@RequestMapping("province")
@CrossOrigin
public class ProvinceController {

    @Autowired
    private ProvinceService provinceService;

    @GetMapping("findByPage")
    public Result findByPage(Integer page,Integer rows){
        Result result = new Result();
        page = page == null ? 1 : page;
        rows = rows == null ? 4 : rows;
        List<Province> provinces = provinceService.findByPage(page, rows);
        Integer totals = provinceService.findTotals();
        Integer totalsPage = totals % rows == 0 ? totals / rows : totals / rows + 1;
        result.setProvinces(provinces).setTotals(totals).setTotalsPage(totalsPage).setPage(page);
        return result;
    }

    @PostMapping("save")
    public Result saveProvince(@RequestBody Province province){
        Result result = new Result();
        try {
            provinceService.save(province);
            result.setFlag(true).setMessage("保存成功！");
        } catch (Exception e) {
            result.setMessage("保存失败，请稍后重试！");
        }
        return result;
    }


    @GetMapping("delete")
    public Result deleteById(String id){
        Result result = new Result();
        try {
            provinceService.delete(id);
            result.setFlag(true);
        } catch (Exception e) {
            result.setMessage("删除失败，请稍后重试！");
        }
        return result;
    }

    @PostMapping("update")
    public Result updateById(String id,@RequestBody Province province1){
        Province province = provinceService.findAll(id);
        province.setName(province1.getName());
        province.setTags(province1.getTags());
        Result result = new Result();
        try {
            provinceService.update(province);
            result.setFlag(true);
        } catch (Exception e) {
            result.setMessage("更新失败，请稍后重试！");
        }
        return result;
    }

}
